<?php

namespace app\model;

use think\Model;

/**
 * @property integer $create_time 创建时间
 * @property integer $id 主键(主键)
 * @property string $key 键
 * @property string $prefix 前缀
 * @property integer $update_time 更新时间
 * @property string $value 值
 */
class Config extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'kllxs_config';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $pk = 'id';

    /**
     * 查询 function
     *
     * @param mixed $field     查询字段
     * @param mixed $op        查询表达式
     * @param mixed $condition 查询条件
     * @return array
     */
    public static function select($field, $op = null, $condition = null): array
    {
        $all = Config::where($field, $op, $condition)->select();
        $data = [];
        foreach ($all as $k => $v) {
            $data[$v["key"]] = $v;
        }
        return $data;
    }

    /**
     * 保存 function
     *
     * @param array $data
     * @param string $prefix
     * @return boolean
     */
    public static function saves(array $data, string $prefix): bool
    {
        $res = true;
        foreach ($data as $k => $v) {
            $find = Config::where("prefix", $prefix)->where("key", $k)->find();
            if ($find) {
                $update = Config::update(["value" => $v], [["prefix", "=", $prefix], ["key", "=", $k]]);
                if (!$update) {
                    $res = false;
                }
            } else {
                $create = Config::create(["key" => $k, "value" => $v, "prefix" => $prefix]);
                if (!$create) {
                    $res = false;
                }
            }
        }
        return $res;
    }
}
